<template>
    <div id="blog">
        <div class="bg_wrap">
            <header style="text-align:left">
                <a-input style="margin:20px;max-width:500px" v-model:value="markdownOptions.input_title" placeholder="标题" />

                    <a-select
                            v-model:value="value"
                            mode="multiple"
                            style="max-width: 250px;min-width:100px"
                            placeholder="选择分类"
                            option-label-prop="label"

                    >
                        <a-select-option v-for="(v, k, index) in selectType" :value=k :label=v>
                            {{v}}
                        </a-select-option>

                    </a-select>


                <div style="margin-left:20px;max-width:500px">
                    <a-textarea
                            v-model:value="markdownOptions.desc"
                            placeholder="描述"
                            :auto-size="{ minRows: 2, maxRows: 5 }"
                    />
                </div>

            </header>
            <div class="mavonEditor" style="margin:10px">
                <v-md-editor
                              :disabled-menus="[]"
                              @upload-image="handleUploadImage"
                              v-model="markdownOptions.html"
                              height="400px"
                        @copy-code-success="handleCopyCodeSuccess">

                </v-md-editor>

            </div>

            <a-button class="commitbtn" type="primary" @click="add">
                {{markdownOptions.btnText}}
            </a-button>
        </div>


    </div>
</template>

<script>
    import { addArticle, selectById, editArticle } from "@/api/article/index"
    import {useRoute} from 'vue-router';

    import { defineComponent, onMounted, reactive, ref, watch, components } from 'vue';
    import { message } from 'ant-design-vue';
    import axios from 'axios'

    import VMdPreviewHtml from '@kangc/v-md-editor/lib/preview-html';
    import createCopyCodePreview from '@kangc/v-md-editor/lib/plugins/copy-code/preview';
    import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';

    import { getCookie } from "@/util/getCookieByName"
    import { editSelf } from "@/api/user/index"
    VMdPreviewHtml.use(createCopyCodePreview());



    // import msgTip from '../msgTip'
    export default defineComponent({

        setup (){

            const markdownOptions = reactive({content: '', // 输入的markdown
                html: '', // 及时转的html
                input_title: '',
                handbook: '',
                btnText: '发表',
                desc: ''
            });
            const route = useRoute();
            const articleId =  route.query.aid;


            const selectType = {
                    1: '前端',
                    2: '后端',
                    3: '其他'
                };
            const value = ref([]);
            const watchSelect = ref([]);

            const  change = (value, render) => {
                        // render 为 markdown 解析后的结果[html]
                markdownOptions.html = render
            };


            /**
             * 上传图片
             * */
            const handleUploadImage = (event, insertImage, files)=>{

                // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
                let data = new FormData();
                data.append('file', files[0]);

                //上传图片
                axios.post("http://112.74.55.150:8087/homeImageUpload", data).then(res=>{
                    console.log(res.data);
                    insertImage({
                        url: res.data,
                        desc: '图片',
                    });
                    // markdownOptions.html += "![Description]("+res.data+")"
                })
            };


            /**
             * 添加
             * */
            const add = () => { // 添加提交


                watchSelect.value = [];
                value.value.forEach(item=>{
                    watchSelect.value.push({
                        label: selectType[item],
                        value: item
                    })
                });

                // watchSelect.value
                console.log(markdownOptions.input_title)
                if(markdownOptions.input_title=="" || markdownOptions.html=="" || markdownOptions.desc=="" || watchSelect.value.length==0) {
                    message.warning("有选项为空！");
                    return;
                }



                let editParams = {
                    title: markdownOptions.input_title,
                    content: markdownOptions.html,
                    nativeContent:markdownOptions.handbook,
                    uid:JSON.parse(localStorage.getItem("my-admin-id")) || 6,
                    author: localStorage.getItem("my-admin-username") || "123",
                    tag: JSON.stringify(watchSelect.value),
                    description: markdownOptions.desc
                };

                if(articleId){
                    editParams.id = articleId;
                    updateArticle (editParams).then(res=>{
                        if(res){
                            updateCommit(editParams)
                        }
                    });
                    return;
                }


                addArticle(JSON.stringify(editParams)).then(data => {
                    console.log(data);
                    // checkStatus(data.code);
                    if(data.code==200){
                        message.success("上传成功！");
                        setTimeout(() => {
                            markdownOptions.input_title = "";
                            markdownOptions.handbook = "";
                        }, 1000)
                    }else{
                        message.error(data.msg)
                    }
                });
            };

            /**
             * 编辑 提交
             * */
            const updateArticle = (editParams)=>{
                let uuid = getCookie("ps");
                if(!editParams.id && !uuid) return message.error("id为空");

                return new Promise(resolve => {
                    editSelf({uid: editParams.uid, uuid}).then(res=>{
                        if(res){
                            resolve(res)
                        }else{
                            message.warning("不能修改别人的文章");
                        }
                    })
                })


            };

            /**
             * 修改提交
             * */
            const updateCommit = (data) => {
                editArticle(JSON.stringify(data)).then(res=>{
                    if(res.code===200) return message.success(res.msg)
                    message.warning(res.msg)
                })
            };



            /**
             * 编辑展示
             * */
            const showArticle = () => {
                if(!articleId) return;

                selectById({id: articleId}).then(res=>{
                    let editContent = res.list;
                    markdownOptions.html = editContent.content;
                    markdownOptions.input_title = editContent.title;
                    markdownOptions.desc = editContent.description;
                    markdownOptions.btnText = "修改";
                    console.log(typeof editContent.tag);
                    let tag = JSON.parse(editContent.tag);
                    tag.forEach(item=>{
                        value.value.push(item.value)
                    });
                })
            };

            /**
             * 复制
             * @param code
             */
            const  handleCopyCodeSuccess = (code) => {
                console.log(code);
            };


            onMounted(showArticle);


            watch(value, val => {
                console.log(`selected:`, val);
            });



            return {
                markdownOptions,
                components,
                selectType,
                value,
                watchSelect,
                change,
                handleUploadImage,
                add,
                showArticle,
                handleCopyCodeSuccess,
                articleId,
                updateArticle,
                updateCommit

            }
        }
    })

</script>

<style lang="scss">

    .commitbtn{
        /*position: relative;*/
        /*right: 40%;*/
        /*top: 20px;*/
    }
    .v-note-wrapper{
        z-index: 99 !important;
    }

</style>
